package cn.wolfcode.p2p.base.exception;

import cn.wolfcode.p2p.base.util.JSONResult;
import org.springframework.ui.Model;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;


@ControllerAdvice
public class ErrorControllerAdvice {

    // 只会针对指定异常类型做处理
    @ExceptionHandler(RuntimeException.class)
    public String handle(Exception ex, Model model) {
        model.addAttribute("error", ex.getMessage());
        return "err";
    }

    @ExceptionHandler(CustomerException.class)
    @ResponseBody
    public JSONResult handleJSONException(Exception ex) {
        JSONResult result = new JSONResult();
        result.mark(ex.getMessage());
        return result;
    }


    @ExceptionHandler(BindException.class)
    @ResponseBody
    public JSONResult handleJSONException2(BindException bindEx) {
        JSONResult result = new JSONResult();
        List<ObjectError> allErrors = bindEx.getAllErrors();
        StringBuilder sb = new StringBuilder(40);
        for (ObjectError error : allErrors) {
            sb.append(error);
        }
        result.mark(sb.toString());
        return result;
    }

}
